package org.foreveross.que.applicationImpl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.PersistenceException;

import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cjk.CJKAnalyzer;
//import org.apache.lucene.queryParser.QueryParser;
//import org.apache.lucene.queryParser.MultiFieldQueryParser;

import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.util.Version;
import org.foreveross.que.entity.SayEntity;
import org.foreveross.que.entity.TopicEntity;
import org.foreveross.que.infra.TopicRepository;
import org.foreveross.que.infra.base.constant.SysConstants;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.FullTextQuery;
import org.hibernate.search.jpa.Search;
//import org.apache.lucene.analysis.standard.StandardAnalyzer;
//import org.apache.lucene.queryParser.MultiFieldQueryParser;
//import org.apache.lucene.queryParser.QueryParser;
//import org.apache.lucene.search.BooleanClause;
//import org.apache.lucene.search.Query;
//import org.apache.lucene.util.Version;
//import org.hibernate.search.jpa.FullTextEntityManager;
//import org.hibernate.search.jpa.FullTextQuery;
//import org.hibernate.search.jpa.Search;
import org.openkoala.koala.auth.ss3adapter.AuthUserUtil;
import org.openkoala.koala.auth.ss3adapter.CustomUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.foreveross.que.application.TopicApplication;
import org.foreveross.que.vo.IndexVo;
import org.foreveross.que.vo.PageData;
import org.foreveross.que.vo.TopicVo;

@SuppressWarnings({ "unchecked", "rawtypes" })
@Service
public class TopicApplicationImpl implements TopicApplication {

	@Autowired
	TopicRepository topicRepository;
	
	public void loadTopics(IndexVo vo, List<String> availMenus)
			throws Exception {
		PageData pageData = vo.getPageData();
		Map params = this.loadParams(vo, availMenus);
		List<TopicEntity> entitys = topicRepository.findSubjects(params,
				pageData.getPageIndex(), pageData.getPageLen());
		Long dataSize = topicRepository.findSubjectsCount(params);
		pageData.setResult(getTopicVos(entitys));
		pageData.setDataSize(dataSize);
	}

	/**
	 * 装在查询参数
	 * 
	 * @param vo
	 *            页面vo
	 * @param availMenus
	 *            权限权限讨论区集合（这个扩展）
	 * @return
	 * @throws Exception
	 */
	private Map loadParams(IndexVo vo, List<String> availMenus)
			throws Exception {
		Map map = new HashMap();
		map.put("title", vo.getTitle());
		if (StringUtils.isBlank(vo.getMid()) && availMenus != null
				&& availMenus.size() != 0) {
			map.put("mid", availMenus);
		} else {
			map.put("mid", vo.getMid());
		}
		map.put("sysType", vo.getSysType());

		if (StringUtils.equals("three", vo.getSearchType())) {
			CustomUserDetails user = vo.getLoginUser();
			map.put("createAccount", user.getUsername());
		} else {
			map.put("searchType", vo.getSearchType());
		}
		return map;
	}

	/**
	 * 将topic实体集合转化成vo集合
	 * 
	 * @param entitys
	 *            实体集合
	 * @return vo集合
	 * @throws Exception
	 */
	private List getTopicVos(List<TopicEntity> entitys) throws Exception {
		List topics = new ArrayList();
		for (TopicEntity entity : entitys) {
			TopicVo vo = new TopicVo();
			vo.load(entity);
			topics.add(vo);
		}
		return topics;
	}

	@Transactional
	@Override
	public void updateIsStickie(String id, Integer type) throws Exception {
		TopicEntity entity = this.topicRepository.get(TopicEntity.class, id);
		entity.setIsStickie(type);
	}

	public void loadTopic(IndexVo vo) throws Exception {
		TopicEntity entity = this.topicRepository.get(TopicEntity.class,
				vo.getTid());
		TopicVo tvo = vo.getTopicVo();

		tvo.loadSayTopic(entity);

	}

	@Transactional
	@Override
	public TopicEntity launchTopic(IndexVo vo) throws Exception {
		if (StringUtils.isBlank(vo.getMid())) {
			vo.setMsg("所属功能不能确定！");
			return null;
		}
		TopicVo topicVo = vo.getTopicVo();
		CustomUserDetails user = vo.getLoginUser();
		String username = null;
		if(user!=null){
			username = user.getUsername();
		}else{
			
		}
		TopicEntity entity = new TopicEntity();
		Date currDate = new Date();
		entity.setIsStickie(SysConstants.NO_STICKIE);
		entity.setBrowseCount(SysConstants.ZERO_INT);
		entity.setCreateTime(currDate);
		entity.setCreateAccount(username);
		entity.setCreateUrole(topicVo.getCreateUrole());
		entity.setLastTime(currDate);
		entity.setMid(vo.getMid());
		entity.setReplyCount(SysConstants.ZERO_INT);
		entity.setState(1);
		entity.setCreateAccount(username);
		entity.setTitle(topicVo.getTitle());
		entity.setSubjectInfo(topicVo.getSubjectInfo());
		entity.setSysType(vo.getSysType());
		this.topicRepository.create(entity);
		return entity;
	}

}
